package com.LeeCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 划分字母区间
 */

public class Code763 {
    public static void main(String[] args) {
        String s = "eccbbbbdec";
        System.out.println(new Code763().partitionLabels(s));

    }

    public List<Integer> partitionLabels(String s) {
        List<Integer> ans = new ArrayList<>();
        int[] aux = new int[s.length()];
        Map<Character, Integer> map = new HashMap<>();

        for (int i = s.length() - 1; i >= 0; i--) {
            if (!map.containsKey(s.charAt(i))) {
                aux[i] = i;
            } else {
                aux[i] = map.get(s.charAt(i));
            }
            map.put(s.charAt(i), i);
        }

        int start = 0, boundary = aux[0];
        for (int i = 0; i < s.length(); i++) {
            boundary = Math.max(boundary, aux[i]);
            if (i == boundary) {
                ans.add(boundary - start + 1);
                boundary ++;
                start = boundary;
            }
        }
        return ans;
    }

    public List<Integer> partitionLabels1(String s) {
        int[] last = new int[26];
        int length = s.length();
        for (int i = 0; i < length; i++) {
            last[s.charAt(i) - 'a'] = i;
        }
        List<Integer> partition = new ArrayList<Integer>();
        int start = 0, end = 0;
        for (int i = 0; i < length; i++) {
            end = Math.max(end, last[s.charAt(i) - 'a']);
            if (i == end) {
                partition.add(end - start + 1);
                start = end + 1;
            }
        }
        return partition;
    }
}
